#include <iostream>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include "protocol/include/log.hpp"
#include "protocol/include/MIRPParser.hpp"
#include <thread>
#include <chrono>

using namespace std;

static MIRPParser *parser;

static volatile bool running = true;

const int port = 9013;

static bool udp_sender(int sock, struct sockaddr_in *server_addr)
{
    MIRPHeader *header = parser->getMIRP();
    if (header)
    {
        sendto(sock, header, header->length + sizeof(MIRPHeader), 0, (struct sockaddr *)server_addr, sizeof(struct sockaddr_in));
        return true;
    }
    else
        return false;
}

void udp_main()
{
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cout << "socket error" << endl;
        return;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr("0.0.0.0");

    parser = new MIRPParser("/home/wang/Documents/github/internship/shang-hai-qi-huo/udp.pcap");

    parser->parse();

    std::this_thread::sleep_for(std::chrono::seconds(1));

    while (running && udp_sender(sock, &server_addr))
    {
        usleep(5 * 1000);
    }

    LOG("no more mirp to send\n");

    delete parser;
}

void udp_exit()
{
    LOG("udp exiting\n");
    running = false;
    return;
}
